﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Principal;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using Code.Models;
using QianBuo.Lottery.Web.Models;
//using Spark.Web.Mvc;

namespace QianBuo.Lottery.Web
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            var setts = System.Configuration.ConfigurationManager.AppSettings;
            string ext = null;
            ext = setts["UrlExt"];
            if (string.IsNullOrEmpty(ext))
                ext = "";
            else if (!ext.StartsWith("."))
                ext = "." + ext;

            routes.MapRoute(
                "Commen", // 公用
                "C/{action}/{id}", // 带有参数的 URL
                new { controller = "Commen", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

            routes.MapRoute(
                "Play_Single", // 单式购彩
                "Lottery/S/{id}/{p1}" + ext, // 带有参数的 URL
                new { controller = "Play", action = "SinglePlay", id = UrlParameter.Optional, p1 = UrlParameter.Optional }, // 参数默认值
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );

            routes.MapRoute(
                "Play", // 购彩
                "Lottery/{id}/{p1}", // 带有参数的 URL
                new { controller = "Play", action = "Index", id = UrlParameter.Optional, p1 = UrlParameter.Optional }, // 参数默认值
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );

            routes.MapRoute(
                "PlayType", // 玩法
                "Lottery/{id}/T/{p1}" + ext, // 带有参数的 URL
                new { controller = "Play", action = "Play", id = UrlParameter.Optional, p1 = UrlParameter.Optional }, // 参数默认值
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );


            routes.MapRoute(
                "Home_default.html1",
                "{controller}" + ext,
                new { controller = "Home", action = "Index" },
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );
            routes.MapRoute(
                "Home_default.html3",
                "{controller}/{action}/{id}" + ext,
                new { controller = "Home", action = "Index" },
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );
            routes.MapRoute(
                "Home_default.html2",
                "{controller}/{action}" + ext,
                new { controller = "Home", action = "Index" },
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );


            routes.MapRoute(
                "Default", // 默认
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
                new string[] { "QianBuo.Lottery.Web.Controllers" }
            );

        }

        protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            var path = this.Server.MapPath("~/Content/thems");
            System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(path);
            var files = info.GetFileSystemInfos();
            var thems = new List<string>();
            foreach (var item in files)
            {
                if (item.Extension == ".jpg")
                {
                    thems.Add(item.Name.Substring(0, item.Name.LastIndexOf('.')));
                }
            }
            Global.Thems = thems.ToArray();

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomComparisonAttribute), typeof(ComparisonValidator));

        }

        protected void FormsAuthentication_Authenticate(object sender, FormsAuthenticationEventArgs e)
        {

            if (Request != null && Request.Url != null)
            {
                if (!Code.BLL.CacheManage.IsRegest(Request.Url.Host))
                {
                    Response.Write("您输入的地址("+Request.Url.ToString()+")未找到！");
                    Response.End();
                    return;
                }
            }

            if (FormsAuthentication.CookiesSupported)
            {
                HttpCookie authtick = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authtick == null)
                    return;

                FormsAuthenticationTicket tick = FormsAuthentication.Decrypt(authtick.Value);
                
                if (tick == null || tick.Expired)
                    return;
                var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;
                if (aus != null && aus.Forms.SlidingExpiration && (tick.Expiration - DateTime.Now).TotalMinutes > aus.Forms.Timeout.TotalMinutes / 2)
                {
                    tick = new FormsAuthenticationTicket(2, tick.Name, tick.IssueDate, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, tick.UserData);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                    Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                    Response.Cookies.Add(cookie);
                }

                var data = tick.Name.Split('&').ToDictionary(p => p.Split(':')[0], p => p.Split(':')[1]);
                List<string> roles = new List<string>();
                var r = Code.BLL.CacheManage.Authentication;
                if (data.ContainsKey("RoleID") && r.Count > 0)
                {
                    int roleid = int.TryParse(data["RoleID"], out roleid) ? roleid : -1;
                    var role = Code.BLL.CacheManage.Roles[roleid];
                    if (role != null && role.State == (short)RoleState.Enable)
                        roles = r.Values.Where(p => p.RolesID == roleid && p.State == (short)Code.Models.AuthenticationState.Enable && p.Authority.State == (short)Code.Models.AuthorityState.Enable)
                            .Select(p => p.Authority.AuthorityKey).ToList();
                }

                roles.AddRange(data["Roles"].Split(',').Where(p => !roles.Contains(p)));

                Context.User = new GenericPrincipal(new GenericIdentity(tick.Name), roles.ToArray());
            }
        }
        protected void Session_End(object sender, EventArgs e)
        {
            Guid? uid = Session["Login_Uid"] as Guid?;
            Guid? manage = Session["AdminID"] as Guid?;
            if (uid.HasValue)
            {
                lock (Global.OnLineUsers)
                {
                    Application.AllKeys.Where(p => p.StartsWith("OnLineUser_")).Select(p => new Guid(p.Remove(0, 11)));
                    Global.OnLineUsers.Remove(uid.Value);
                }
            }
            if (manage.HasValue)
            {
                lock (Global.OnLineManagers)
                {
                    Global.OnLineManagers.Remove(manage.Value);
                }
            }

        }

    }

    public static class Global
    {
        static Global()
        {
            OnLineUsers = new HashTable<Guid, UserModel>();
            OnLineManagers = new HashTable<Guid, AdminModel>();
        }
        public static HashTable<Guid, UserModel> OnLineUsers { get; private set; }
        public static HashTable<Guid, AdminModel> OnLineManagers { get; private set; }
        public static string[] Thems { get; set; }
    }
}